package com.lanhao.aot.carrierintegration.rupost;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils;
import com.aliyun.openservices.shade.org.apache.commons.lang3.tuple.Pair;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

public class RussianPostUtil {
	private static final Logger LOG = LoggerFactory.getLogger(RussianPostUtil.class);
	public static final String MAIN_HOST = "http://119.28.3.82:8082";
	public static final String PRINT_HOST = "http://119.28.3.82:8089";
	public static final String USER_NAME = "YKJGYL";
	public static final String PASSWORD = "123456";
	public static final String FORMAT = "A4_EMS_BGD.frx";
	public static final String PrintType = "1";
	public static final String PRODUCT_ID = "2621";
	public static final String TRADE_TYPE = "ZYXT";
	public static final String FILE_TYPE = "PDF";
	public static final String AUTH_URL = MAIN_HOST + "/selectAuth.htm?username={}&password={}";
	public static final String PRODUCT_URL = MAIN_HOST + "/getProductList.htm";
	public static final String ORDER_URL = MAIN_HOST + "/createOrderApi.htm";
	public static final String PRINT_URL = PRINT_HOST
			+ "/order/FastRpt/PDF_NEW.aspx?Format={}&PrintType=lab10_10&order_id={}";

	public static void main(String[] args) {
		createAndPrintOrder();
//		printLabel("10858436", "CGSRU0300007021YQ");
	}

	public static Pair<String, String> selectAuth() {
		String authUrl = StrUtil.format(AUTH_URL, USER_NAME, PASSWORD);
		String response = HttpRequest.get(authUrl).execute().body();
		LOG.info("调用鉴权接口URL={}，reponse={}", authUrl, response);
		if (StringUtils.isNotBlank(response)) {
			JSONObject responseObject = JSON.parseObject(response);
			Boolean ack = responseObject.getBoolean("ack");
			if (ack) {
				String customerId = responseObject.getString("customer_id");
				String customerUserId = responseObject.getString("customer_userid");
				return Pair.of(customerId, customerUserId);
			}
		}
		return null;
	}

	public static void createAndPrintOrder() {
		Pair<String, String> authPair = selectAuth();
		if (authPair == null) {
			return;
		}
		String customerId = authPair.getLeft();
		String customerUserId = authPair.getRight();
		JSONObject paramValue = new JSONObject();
		paramValue.put("buyerid", "");
//		paramValue.put("consignee_mobile", "");
		// 仓库地址
		paramValue.put("consignee_address", "Московская область, город Подольск, ул.Станционная 22.");
		paramValue.put("consignee_city", "Подольск");
		paramValue.put("order_returnsign", "N");
		paramValue.put("consignee_name", "Евгений Ринатович");
		paramValue.put("consignee_postcode", "385011");
		paramValue.put("consignee_state", "Московская область");
		paramValue.put("consignee_telephone", "+7(999)861-49-23");
		paramValue.put("country", "RU");
		paramValue.put("customer_id", customerId);
		paramValue.put("customer_userid", customerUserId);

		paramValue.put("trade_type", TRADE_TYPE);
		paramValue.put("product_id", PRODUCT_ID);
//		paramValue.put("order_customerinvoicecode", "");
//		paramValue.put("weight", "");
//		paramValue.put("product_imagepath", "");
//		paramValue.put("order_transactionurl", "");
//		paramValue.put("consignee_email", "");
//		paramValue.put("consignee_companyname", "");
//		paramValue.put("order_cargoamount", "");
//		paramValue.put("order_insurance", "");

//		JSONArray items = new JSONArray();
//		JSONObject item = new JSONObject();
//		item.put("invoice_amount", "");
//		item.put("invoice_pcs", "");
//		item.put("invoice_title", "");
//		item.put("invoice_weight", "");
//		item.put("item_id", "");
//		item.put("item_transactionid", "");
//		item.put("sku", "");
//		item.put("sku_code", "");
//		item.put("hs_code", "");
//		items.add(item);

//		paramValue.put("orderInvoiceParam", items);

		String strParam = paramValue.toString();

		String response = HttpRequest.post(ORDER_URL).form("param", strParam).execute().body();
		LOG.info("创建订单url={}, param={}, 返回结果response={}", ORDER_URL, strParam, response);
		if (StringUtils.isNotBlank(response)) {
			JSONObject responseObject = JSON.parseObject(response);
			String message = StringUtils.EMPTY;
			try {
				message = URLDecoder.decode(responseObject.getString("message"), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			Boolean ack = responseObject.getBoolean("ack");
			LOG.info("返回结果ack={}, message={}", ack, message);
			if (ack) {
				String trackingNumber = responseObject.getString("tracking_number");
				String orderId = responseObject.getString("order_id");
				if (StringUtils.isNotBlank(orderId)) {
					printLabel(orderId, trackingNumber);
				}
			}
		}
	}

	public static void printLabel(String orderId, String trackingNumber) {
		String printUrl = StrUtil.format(PRINT_URL, "A4_EMS_BGD.frx", orderId);
		HttpResponse execute = HttpRequest.get(printUrl).setMaxRedirectCount(1).execute();
		String localFilePath = "D:/" + orderId + "_" + trackingNumber + "." + FILE_TYPE;
		execute.writeBody(new File(localFilePath));
		LOG.info("打印标签url={}, 存储到本地路径为：{}", printUrl, localFilePath);
	}
	
}
